//
//  ZZCWKExtension.swift
//  ewgShop
//
//  Created by zzc on 2019/8/5.
//  Copyright © 2019 zzc. All rights reserved.
//

import Foundation
import UIKit
import ObjectiveC.runtime
import WebKit


extension CDVIntentAndNavigationFilter : NSSwiftyLoadProtocol
{
    
    @objc func shouldOpenURLRequestWithWkNavigationType(request:NSURLRequest,navigationType:WKNavigationType) -> Bool {
        return navigationType == WKNavigationType.linkActivated || (navigationType == WKNavigationType.other && (request.mainDocumentURL!.absoluteString as NSString).isEqual(to: (request.url!.absoluteString))) || ((request.url?.scheme as NSString?)?.isEqual(to: "http") == false && (request.url?.scheme as NSString?)?.isEqual(to: "https") == false)
    }
    
    @objc static func shouldOverrideLoadSwizzle(request:NSURLRequest,navigationType:WKNavigationType,filterValue:CDVIntentAndNavigationFilterValue) -> Bool {
        
        let allowIntents_whitelistRejectionFormatString = "ERROR External navigation rejected - <allow-intent> not set for url='%@'"
        
        let allowNavigations_whitelistRejectionFormatString = "ERROR Internal navigation rejected - <allow-navigation> not set for url='%@'"
        
        let url = request.url
        
        var wkFilterValue = filterValue
        
        if filterValue == CDVIntentAndNavigationFilterValue.noneAllowed {
            if ((request.url?.host) != nil) &&
                (request.url?.scheme as NSString?)?.isEqual(to: "http")==false &&
                (request.url?.scheme as NSString?)?.isEqual(to: "https")==false {
                wkFilterValue = CDVIntentAndNavigationFilterValue.intentAllowed
            }
            
            if (request.url?.absoluteString as NSString?)?.range(of: "base64").length ?? 0 > 0 {
                wkFilterValue = CDVIntentAndNavigationFilterValue.navigationAllowed
            }
        }
        
        switch wkFilterValue {
        case CDVIntentAndNavigationFilterValue.navigationAllowed:
            return true
        case CDVIntentAndNavigationFilterValue.intentAllowed:
            if self.responds(to: #selector(shouldOpenURLRequestWithWkNavigationType(request:navigationType:))){
                
                if #available(iOS 10.0, *){
                    if (UIApplication.shared.responds(to: #selector(UIApplication.open(_:options:completionHandler:)))){
                    UIApplication.shared.open(url!, options: [:], completionHandler: nil)
                    }else{
                        UIApplication.shared.openURL(url!)
                    }
                }
            }else{
                UIApplication.shared.openURL(url!)
            }
            return false
        case CDVIntentAndNavigationFilterValue.noneAllowed:
            print("\(String.init(format: "%@%@", allowNavigations_whitelistRejectionFormatString,url?.absoluteString ?? ""))")
            if navigationType == WKNavigationType.linkActivated{
                print("\(String.init(format: "%@%@", allowIntents_whitelistRejectionFormatString,url?.absoluteString ?? ""))")
            }
            return false
        @unknown default:
            return false
        }
    }
    
    public static func swiftyLoad() {
        print("CDVIntentAndNavigationFilter -> swiftyLoad")
        let originalMethod = class_getClassMethod(CDVIntentAndNavigationFilter.self, #selector(shouldOverrideLoad(with:navigationType:filterValue:)))
        
//        var methodCount : UInt32 = 0;
//        var methodlist = class_copyMethodList(CDVIntentAndNavigationFilter.self, &methodCount)
//        var methodsArray = NSMutableArray.init(capacity: Int(methodCount));
//        for i in 0..<methodCount {
//
//            let temp : Method = (methodlist?[Int(i)])!
//
//            let imp : IMP = method_getImplementation(temp)
//
//            let name_f = method_getName(temp)
//
//            let name_s = sel_getName(method_getName(temp))
//
//            let arguments = method_getNumberOfArguments(temp)
//
//            let encoding = method_getTypeEncoding(temp)
//
//            print("方法名:\(NSString.init(utf8String: name_s))")
//        }
        
        let methodSwizzlingMethod = class_getClassMethod(CDVIntentAndNavigationFilter.self, #selector(shouldOverrideLoadSwizzle(request:navigationType:filterValue:)))
        
        if originalMethod != nil && methodSwizzlingMethod != nil {
            method_exchangeImplementations(originalMethod!, methodSwizzlingMethod!)
        }
    }

}


extension UIViewController {
    
    static func yy_swizzle() {
        guard let m1 = class_getInstanceMethod(self, #selector(viewWillAppear(_:))) else {
            return
        }
        guard let m2 = class_getInstanceMethod(self, #selector(swizzle_viewWillAppear(_:))) else {
            return
        }
        
        if (class_addMethod(self, #selector(swizzle_viewWillAppear(_:)), method_getImplementation(m2), method_getTypeEncoding(m2))) {
            class_replaceMethod(self, #selector(swizzle_viewWillAppear(_:)), method_getImplementation(m1), method_getTypeEncoding(m1))
        } else {
            method_exchangeImplementations(m1, m2)
        }
    }
    
    @objc func swizzle_viewWillAppear(_ animated: Bool) {
        swizzle_viewWillAppear(animated)
        print("swizzle_viewWillAppear")
    }
}


